import { uploadInfo } from '@/common/config'
const { OSSAccessKeyId, signature, policy, url, endPoint, bucket, stsServer } = uploadInfo

export default function(files, dir) {
  // #ifdef APP-PLUS
  /**
	 * app端的初始化方法
	 * */
  var appOss = uni.requireNativePlugin('MZ-AliyunOss')
  appOss.init({
    stsServer,
    endPoint,
    docPath: plus.io.convertLocalFileSystemURL('_doc')
  }, (ret) => {
    if (!ret.status) {
      console.log('oss初始化失败')
    }
  })
  // #endif

  return new Promise((resolve) => {
    const fileArr = []
    // uni.showLoading({title: "上传中"});
    const size = files.length
    const proList = new Array(size).fill(0)
    for (let index = 0; index < files.length; index++) {
      const file = files[index]
      let fileName
      /* #ifndef APP-PLUS*/
      fileName = file
        .replace('wxfile://', '')
        .replace('http://tmp/', '')
      /* #endif*/
      /* #ifdef APP-PLUS*/
      const path = plus.io.convertLocalFileSystemURL(file.path ? file.path : file)
      const subfix = path.substr(path.lastIndexOf('.'))
      fileName = randomString() + subfix
      /* #endif*/
      const filePath = setPath() + fileName
      /* #ifdef MP*/
      const uploadTask = uni.uploadFile({
        url, // 这是你自己后台的连接
        filePath: file,
        name: 'file', // 后台要绑定的名称
        header: {
          'Content-Type': 'multipart/form-data'
        },
        // 参数绑定
        formData: {
          name: filePath,
          key: filePath,
          policy,
          OSSAccessKeyId,
          success_action_status: '200',
          signature
        },
        success: res => {
          fileArr.push(url + '/' + filePath)
          if (fileArr.length === files.length) {
            uni.hideLoading()
            resolve(fileArr)
          }
        }
      })

      uploadTask.onProgressUpdate((res) => {
        const i = res.progress
        proList[index] = i
        let totail = 0
        for (let j = 0; j < size; j++) {
          totail += proList[j]
        }
        const progress = totail / (size * 100)
        uni.showLoading({ title: `上传中:${Math.floor(progress * 100 * 100) / 100}%` })
      })
      /* #endif*/

      // #ifdef APP-PLUS
      let res = {}
      const key = filePath
      appOss.setUploadObjectListener({}, ret => {
        if (ret.eventType && ret.eventType === 'onSuccess') {
          fileArr.push(url + '/' + filePath)
          if (fileArr.length === files.length) {
            uni.hideLoading()
            resolve(fileArr)
          }
        }
      })
      appOss.uploadObject({
        bucket,
        key,
        path
      }, ret => {
        if (!ret.status) {
          res = {
            title: '请求出错',
            content: '请求出错：' + ret.msg
          }
          resolve(res)
          uni.hideLoading()
        }
      })
      // #endif
    }
  })

  function randomString(len) {
    len = len || 32
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length
    var pwd = ''
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
  }

  function setPath() {
    const date = new Date()
    const url = dir + '/' + date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate() + '/'
    return url
  }
}
